﻿Imports MaasOne.YahooManaged.Finance.Screener.StockCriterias

Namespace YahooManaged.Finance.Screener.API


    Public Class StockScreenerDownload
        Inherits Base.StringDownload

        Public Event AsyncDownloadCompleted(ByVal sender As Base.Download, ByVal e As StockScreenerDownloadCompletedEventArgs)

        Friend mFinanceHelper As New FinanceHelper

        Public Property IgnoreInvalidCriterias As Boolean = False

        Public Function Download(ByVal criterias As IEnumerable(Of StockCriteriaDefinition)) As StockScreenerResponse
            If criterias Is Nothing Then Throw New ArgumentNullException("criterias", "The criterias enumerable is null.")
            Return Me.ToResponse(MyBase.DownloadString(Me.DownloadUrl(criterias)), criterias, False)
        End Function
        Public Function Download(ByVal ids As IEnumerable(Of IID), ByVal criterias As IEnumerable(Of StockCriteriaDefinition)) As StockScreenerResponse
            If ids Is Nothing Then Throw New ArgumentNullException("ids", "The ID Enumerable is null.")
            Dim strIDs As New List(Of String)
            For Each id In ids
                strIDs.Add(id.ID)
            Next
            Return Me.Download(strIDs, criterias)
        End Function
        Public Function Download(ByVal ids As IEnumerable(Of String), ByVal criterias As IEnumerable(Of StockCriteriaDefinition)) As StockScreenerResponse
            If criterias Is Nothing Then Throw New ArgumentNullException("criterias", "The criterias enumerable is null.")
            If ids Is Nothing Then Throw New ArgumentNullException("ids", "The ID Enumerable is null.")
            Dim strIDs As New List(Of String)(ids)
            If strIDs.Count = 0 Then Throw New ArgumentException("ids", "There must be minimum one ID available for downloading.")
            Return Me.ToResponse(MyBase.DownloadString(Me.DownloadUrl(strIDs.ToArray, criterias)), criterias, True)
        End Function

        Public Sub DownloadAsync(ByVal criterias As IEnumerable(Of StockCriteriaDefinition), Optional ByVal userArgs As Object = Nothing)
            If criterias Is Nothing Then Throw New ArgumentNullException("criterias", "The criterias enumerable is null.")
            Dim args As New AsyncArgs(userArgs) With {.Criterias = New List(Of StockCriteriaDefinition)(criterias).ToArray, .Comparing = False}
            MyBase.DownloadStreamAsync(Me.DownloadUrl(args.Criterias), args)
        End Sub
        Public Sub DownloadAsync(ByVal ids As IEnumerable(Of IID), ByVal criterias As IEnumerable(Of StockCriteriaDefinition), Optional ByVal userArgs As Object = Nothing)
            If ids Is Nothing Then Throw New ArgumentNullException("ids", "The ID Enumerable is null.")
            Dim strIDs As New List(Of String)
            For Each id In ids
                strIDs.Add(id.ID)
            Next
            Me.DownloadAsync(strIDs, criterias)
        End Sub
        Public Sub DownloadAsync(ByVal ids As IEnumerable(Of String), ByVal criterias As IEnumerable(Of StockCriteriaDefinition), Optional ByVal userArgs As Object = Nothing)
            If criterias Is Nothing Then Throw New ArgumentNullException("criterias", "The criterias enumerable is null.")
            If ids Is Nothing Then Throw New ArgumentNullException("ids", "The ID Enumerable is null.")
            Dim strIDs As New List(Of String)(ids)
            If strIDs.Count = 0 Then Throw New ArgumentException("ids", "There must be minimum one ID available for downloading.")
            Dim args As New AsyncArgs(userArgs) With {.Criterias = New List(Of StockCriteriaDefinition)(criterias).ToArray, .Comparing = True}
            MyBase.DownloadStreamAsync(Me.DownloadUrl(strIDs.ToArray, criterias), args)
        End Sub

        Private Sub MyBase_DownloadCompleted(ByVal sender As Base.Download, ByVal e As Base.StringDownloadCompletedEventArgs) Handles MyBase.AsyncStringDownloadCompleted
            Dim args As AsyncArgs = CType(e.UserArgs, AsyncArgs)
            Dim resp = Me.ToResponse(e.Response, args.Criterias, args.Comparing)
            RaiseEvent AsyncDownloadCompleted(Me, New StockScreenerDownloadCompletedEventArgs(args.UserArgs, resp, args.Criterias))
        End Sub

        Private Function DownloadUrl(ByVal criterias As IEnumerable(Of StockCriteriaDefinition)) As String
            Dim tags As New List(Of String)
            For Each crit In criterias
                If tags.Contains(crit.CriteriaTag) Then
                    Throw New NotSupportedException("Multiple criterias of same type (except percent/no percent difference) are not supported.")
                Else
                    tags.Add(crit.CriteriaTag)
                End If
            Next

            Dim sb As New Text.StringBuilder
            sb.Append("http://reports.finance.yahoo.com/wr?a0=2.0")
            For Each crit In criterias
                If crit IsNot Nothing AndAlso crit.IsValid Then
                    sb.Append(crit.CriteriaParameter)
                Else
                    If Not Me.IgnoreInvalidCriterias Then
                        Throw New NotSupportedException("Invalid criterias will not be supported. Check out the values of your passed criterias for null values.")
                    End If
                End If
            Next
            sb.Append("&ln=-1")
            Return sb.ToString
        End Function
        Private Function DownloadUrl(ByVal ids() As String, ByVal criterias As IEnumerable(Of StockCriteriaDefinition)) As String
            Dim sb As New Text.StringBuilder(Me.DownloadUrl(criterias))
            sb.Replace("&ln=-1", "")
            sb.Append("&9w=")
            For Each id In ids
                sb.Append(mFinanceHelper.CleanIndexID(id).ToUpper & "_")
            Next
            sb.Remove(sb.Length - 1, 1)
            Return sb.ToString
        End Function

        Private Function ToResponse(ByVal baseResp As Base.StringResponse, ByVal criterias As IEnumerable(Of StockCriteriaDefinition), ByVal comparing As Boolean) As StockScreenerResponse
            Dim results As New List(Of StockScreenerData)
            Dim lines = New List(Of String)(baseResp.Result.Split(New Char() {";"c}, StringSplitOptions.RemoveEmptyEntries))
            If lines.Count > 0 Then

                Dim convCulture As New Globalization.CultureInfo("en-US")

                Dim quoteProps As New List(Of QuoteProperty)
                Dim screenerProps As New List(Of StockScreenerProperty)
                For Each crit In criterias
                    For Each qp In crit.ProvidedQuoteProperties
                        If Not quoteProps.Contains(qp) Then quoteProps.Add(qp)
                    Next
                    For Each sp In crit.ProvidedScreenerProperties
                        If Not screenerProps.Contains(sp) Then screenerProps.Add(sp)
                    Next
                Next

                Dim propertySymbols(-1) As String
                Dim propertyNames(-1) As String
                Dim startIndex As Integer

                If Not comparing Then
                    startIndex = 2
                    propertySymbols = lines(0).Split("|"c)
                    propertyNames = lines(1).Split("|"c)
                Else
                    startIndex = 0
                    Dim lstSymbols As New List(Of String)
                    lstSymbols.Add("")
                    lstSymbols.Add("")
                    lstSymbols.Add("b")
                    lstSymbols.Add("")
                    lstSymbols.Add("c")
                    lstSymbols.Add("8o")
                    lstSymbols.Add("9c")
                    lstSymbols.Add("9t")
                    For Each crt In criterias
                        If crt.ProvidedQuoteProperties.Length > 5 Or crt.ProvidedScreenerProperties.Length > 3 Then
                            lstSymbols.Add(crt.CriteriaTag)
                        End If
                    Next
                    propertySymbols = lstSymbols.ToArray

                    Dim lstNames As New List(Of String)
                    lstNames.Add("Ticker")
                    lstNames.Add("Company Name")
                    lstNames.Add("Last Trade")
                    lstNames.Add("Trade Time")
                    lstNames.Add("Mkt Cap")
                    lstNames.Add("Return On Equity")
                    lstNames.Add("Return On Assets")
                    lstNames.Add("Forward PE")
                    For Each crt In criterias
                        If crt.ProvidedQuoteProperties.Length > 5 Or crt.ProvidedScreenerProperties.Length > 3 Then
                            Select Case crt.CriteriaTag
                                Case "f", "g"
                                    If TypeOf crt Is PriceGainerLosersCriteria Then
                                        Dim mngCrt = CType(crt, PriceGainerLosersCriteria)
                                        If mngCrt.ValueRelativeTo = StockTradingAbsoluteTimePoint.TodaysOpen Then : lstNames.Add("(open)")
                                        Else : lstNames.Add("(close)")
                                        End If
                                    End If
                                Case "h", "i"
                                    If TypeOf crt Is PriceMomentumCriteria Then
                                        Dim mngCrt = CType(crt, PriceMomentumCriteria)
                                        lstNames.Add("(" & mngCrt.RelativeTimeSpanInMinutes.ToString.Replace("_", "") & "m)")
                                    End If
                                Case Else : lstNames.Add("")
                            End Select
                        End If
                    Next
                    propertyNames = lstNames.ToArray

                End If

                For i As Integer = startIndex To lines.Count - 1
                    Dim values() As String = lines(i).Split("|"c)


                    If propertySymbols.Length >= 4 And values.Length = propertySymbols.Length And values.Length = propertyNames.Length Then
                        Dim id As String = values(0)
                        Dim name As String = values(1)
                        Dim lastTradePriceOnly As Double = 0
                        Double.TryParse(values(2), Globalization.NumberStyles.Any, convCulture, lastTradePriceOnly)
                        Dim tradeTime As DateTime = #12:00:00 AM#
                        DateTime.TryParse(values(3), convCulture, Globalization.DateTimeStyles.None, tradeTime)
                        tradeTime = #12:00:00 AM#.AddHours(tradeTime.Hour).AddMinutes(tradeTime.Minute)

                        Dim res As New StockScreenerData(id, name, lastTradePriceOnly, tradeTime, quoteProps.ToArray, screenerProps.ToArray)

                        If values.Length >= 5 Then
                            For p As Integer = 4 To values.Length - 1
                                If values(p) <> String.Empty And values(p) <> "N/A" Then
                                    Dim dblValue As Double = 0
                                    If Double.TryParse(values(p), Globalization.NumberStyles.Any, convCulture, dblValue) OrElse mFinanceHelper.GetMillionValue(values(p)) <> 0 Then

                                        Select Case propertySymbols(p)
                                            Case "c"
                                                res.Values(QuoteProperty.MarketCapitalization) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))
                                            Case "8o"
                                                res.AdditionalValues(StockScreenerProperty.ReturnOnEquity) = dblValue
                                            Case "9c"
                                                res.AdditionalValues(StockScreenerProperty.ReturnOnAssets) = dblValue
                                            Case "9t"
                                                res.AdditionalValues(StockScreenerProperty.ForwardPriceToEarningsRatio) = dblValue
                                            Case "9o"
                                                res.AdditionalValues(StockScreenerProperty.NumberOfEmployees) = dblValue
                                            Case "f"
                                                Dim absoluteChange As Double = dblValue
                                                Dim absolutePreviousValue = res.LastTradePriceOnly - absoluteChange
                                                Dim changeInPercent = absoluteChange / absolutePreviousValue

                                                res.Values(QuoteProperty.ChangeInPercent) = changeInPercent * 100
                                                res.Values(QuoteProperty.Change) = absoluteChange

                                                If propertyNames(p).EndsWith("(open)") Then
                                                    res.Values(QuoteProperty.Open) = absolutePreviousValue
                                                Else
                                                    res.Values(QuoteProperty.PreviousClose) = absolutePreviousValue
                                                End If

                                            Case "g"
                                                Dim changeInPercent As Double = dblValue
                                                Dim absolutePreviousValue = (res.LastTradePriceOnly / (100 + changeInPercent)) * 100
                                                Dim absoluteChange = res.LastTradePriceOnly - absolutePreviousValue

                                                res.Values(QuoteProperty.ChangeInPercent) = changeInPercent
                                                res.Values(QuoteProperty.Change) = absoluteChange

                                                If propertyNames(p).EndsWith("(open)") Then
                                                    res.Values(QuoteProperty.Open) = absolutePreviousValue
                                                Else
                                                    res.Values(QuoteProperty.PreviousClose) = absolutePreviousValue
                                                End If

                                            Case "h"
                                                If criterias IsNot Nothing Then
                                                    Dim context As PriceMomentumCriteria = Nothing

                                                    For Each crit In criterias
                                                        If crit IsNot Nothing AndAlso TypeOf crit Is PriceMomentumCriteria AndAlso CType(crit, PriceMomentumCriteria).PercentValues = False Then
                                                            context = CType(crit, PriceMomentumCriteria)
                                                            Exit For
                                                        End If
                                                    Next
                                                    If context IsNot Nothing Then
                                                        If propertyNames(p).EndsWith("(" & context.RelativeTimeSpanInMinutes.ToString.Replace("_", "") & "m)") Then
                                                            Dim info As New TemporaryPriceChangeInfo
                                                            info.ChangeRelativeTimePoint = context.TimeSpanRelativeTo
                                                            info.ChangeTimeSpan = context.RelativeTimeSpanInMinutes
                                                            info.Change = dblValue * CInt(IIf(context.GainOrLoss = StockPriceChangeDirection.Gain, 1, -1))
                                                            info.ChangeInPercent = info.Change / (res.LastTradePriceOnly - info.Change)
                                                            res.TemporaryLimitedChange = info
                                                        End If
                                                    End If
                                                End If

                                            Case "i"
                                                If criterias IsNot Nothing Then
                                                    Dim context As PriceMomentumCriteria = Nothing
                                                    For Each crit In criterias
                                                        If crit IsNot Nothing AndAlso TypeOf crit Is PriceMomentumCriteria AndAlso CType(crit, PriceMomentumCriteria).PercentValues = True Then
                                                            context = CType(crit, PriceMomentumCriteria)
                                                            Exit For
                                                        End If
                                                    Next
                                                    If context IsNot Nothing Then
                                                        If propertyNames(p).EndsWith("(" & context.RelativeTimeSpanInMinutes.ToString.Replace("_", "") & "m)") Then
                                                            Dim info As New TemporaryPriceChangeInfo
                                                            info.ChangeRelativeTimePoint = context.TimeSpanRelativeTo
                                                            info.ChangeTimeSpan = context.RelativeTimeSpanInMinutes
                                                            info.ChangeInPercent = dblValue * CInt(IIf(context.GainOrLoss = StockPriceChangeDirection.Gain, 1, -1))
                                                            info.Change = res.LastTradePriceOnly - ((res.LastTradePriceOnly / (100 + info.ChangeInPercent)) * 100)
                                                            res.TemporaryLimitedChange = info
                                                        End If
                                                    End If
                                                End If

                                            Case "j"
                                                If criterias IsNot Nothing Then
                                                    Dim context As ExtremePriceCriteria = Nothing
                                                    For Each crit In criterias
                                                        If crit IsNot Nothing AndAlso TypeOf crit Is ExtremePriceCriteria AndAlso CType(crit, ExtremePriceCriteria).PercentValues = False Then
                                                            context = CType(crit, ExtremePriceCriteria)
                                                            Exit For
                                                        End If
                                                    Next
                                                    If context IsNot Nothing Then
                                                        Dim absoluteChange = dblValue * CInt(IIf(context.LessGreater = LessGreater.Greater, 1, -1))
                                                        Dim absolutePreviousValue = res.LastTradePriceOnly - absoluteChange
                                                        Dim changeInPercent = absoluteChange / absolutePreviousValue
                                                        Select Case context.ExtremeParameter
                                                            Case StockExtremeParameter.TodaysHigh
                                                                res.Values(QuoteProperty.DaysHigh) = absolutePreviousValue
                                                            Case StockExtremeParameter.TodaysLow
                                                                res.Values(QuoteProperty.DaysLow) = absolutePreviousValue
                                                            Case StockExtremeParameter.YearsHigh
                                                                res.Values(QuoteProperty.YearHigh) = absolutePreviousValue
                                                                res.Values(QuoteProperty.ChangeInPercentFromYearHigh) = changeInPercent
                                                                res.Values(QuoteProperty.ChangeFromYearHigh) = absoluteChange
                                                            Case StockExtremeParameter.YearsLow
                                                                res.Values(QuoteProperty.YearLow) = absolutePreviousValue
                                                                res.Values(QuoteProperty.PercentChangeFromYearLow) = changeInPercent
                                                                res.Values(QuoteProperty.ChangeFromYearLow) = absoluteChange
                                                        End Select
                                                    End If
                                                End If

                                            Case "k"
                                                If criterias IsNot Nothing Then
                                                    Dim context As ExtremePriceCriteria = Nothing
                                                    For Each crit In criterias
                                                        If crit IsNot Nothing AndAlso TypeOf crit Is ExtremePriceCriteria AndAlso CType(crit, ExtremePriceCriteria).PercentValues = True Then
                                                            context = CType(crit, ExtremePriceCriteria)
                                                            Exit For
                                                        End If
                                                    Next
                                                    If context IsNot Nothing Then
                                                        Dim changeInPercent = dblValue * CInt(IIf(context.LessGreater = LessGreater.Greater, 1, -1))
                                                        Dim absolutePreviousValue = (res.LastTradePriceOnly / (100 + changeInPercent)) * 100
                                                        Dim absoluteChange = res.LastTradePriceOnly - absolutePreviousValue
                                                        Select Case context.ExtremeParameter
                                                            Case StockExtremeParameter.TodaysHigh
                                                                res.Values(QuoteProperty.DaysHigh) = absolutePreviousValue
                                                            Case StockExtremeParameter.TodaysLow
                                                                res.Values(QuoteProperty.DaysLow) = absolutePreviousValue
                                                            Case StockExtremeParameter.YearsHigh
                                                                res.Values(QuoteProperty.YearHigh) = absolutePreviousValue
                                                                res.Values(QuoteProperty.ChangeInPercentFromYearHigh) = changeInPercent
                                                                res.Values(QuoteProperty.ChangeFromYearHigh) = absoluteChange
                                                            Case StockExtremeParameter.YearsLow
                                                                res.Values(QuoteProperty.YearLow) = absolutePreviousValue
                                                                res.Values(QuoteProperty.PercentChangeFromYearLow) = changeInPercent
                                                                res.Values(QuoteProperty.ChangeFromYearLow) = absoluteChange
                                                        End Select
                                                    End If
                                                End If

                                            Case "l"
                                                If criterias IsNot Nothing Then
                                                    Dim context As GapVsPreviousClose = Nothing
                                                    For Each crit In criterias
                                                        If crit IsNot Nothing AndAlso TypeOf crit Is GapVsPreviousClose AndAlso CType(crit, GapVsPreviousClose).PercentValues = False Then
                                                            context = CType(crit, GapVsPreviousClose)
                                                            Exit For
                                                        End If
                                                    Next
                                                    If context IsNot Nothing Then
                                                        res.AdditionalValues(StockScreenerProperty.Gap) = dblValue
                                                    End If
                                                End If

                                            Case "m"
                                                If criterias IsNot Nothing Then
                                                    Dim context As GapVsPreviousClose = Nothing
                                                    For Each crit In criterias
                                                        If crit IsNot Nothing AndAlso TypeOf crit Is GapVsPreviousClose AndAlso CType(crit, GapVsPreviousClose).PercentValues = True Then
                                                            context = CType(crit, GapVsPreviousClose)
                                                            Exit For
                                                        End If
                                                    Next
                                                    If context IsNot Nothing Then
                                                        res.AdditionalValues(StockScreenerProperty.GapInPercent) = dblValue
                                                    End If
                                                End If

                                            Case "o"
                                                If criterias IsNot Nothing Then
                                                    Dim context As PriceToMovingAverageRatioCriteria = Nothing
                                                    For Each crit In criterias
                                                        If crit IsNot Nothing AndAlso TypeOf crit Is PriceToMovingAverageRatioCriteria Then
                                                            context = CType(crit, PriceToMovingAverageRatioCriteria)
                                                            Exit For
                                                        End If
                                                    Next
                                                    If context IsNot Nothing Then
                                                        Dim changeInPercent = dblValue
                                                        Dim maValue = (dblValue / (100 + changeInPercent)) * 100
                                                        Dim absoluteChange = res.LastTradePriceOnly - maValue

                                                        If context.MovingAverage = MovingAverageType.FiftyDays Then
                                                            res.Values(QuoteProperty.FiftydayMovingAverage) = maValue
                                                            res.Values(QuoteProperty.ChangeFromFiftydayMovingAverage) = absoluteChange
                                                            res.Values(QuoteProperty.PercentChangeFromFiftydayMovingAverage) = changeInPercent
                                                        Else
                                                            res.Values(QuoteProperty.TwoHundreddayMovingAverage) = maValue
                                                            res.Values(QuoteProperty.ChangeFromTwoHundreddayMovingAverage) = absoluteChange
                                                            res.Values(QuoteProperty.PercentChangeFromTwoHundreddayMovingAverage) = changeInPercent
                                                        End If
                                                    End If
                                                End If

                                            Case "7"
                                                res.AdditionalValues(StockScreenerProperty.Beta) = dblValue
                                            Case "v"
                                                res.Values(QuoteProperty.PriceSales) = dblValue
                                            Case "e"
                                                res.AdditionalValues(StockScreenerProperty.PriceEarningsRatio) = dblValue
                                            Case "u"
                                                res.Values(QuoteProperty.PEGRatio) = dblValue
                                            Case "9p"
                                                res.AdditionalValues(StockScreenerProperty.EntityValue) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))
                                            Case "9q"
                                                res.AdditionalValues(StockScreenerProperty.EntityValueToRevenueRatio) = dblValue
                                            Case "9r"
                                                res.AdditionalValues(StockScreenerProperty.EntityValueToOperatingCashFlowRatio) = dblValue
                                            Case "9s"
                                                res.AdditionalValues(StockScreenerProperty.EntityValueToFreeCashFlowRatio) = dblValue
                                            Case "x"
                                                res.Values(QuoteProperty.EPSEstimateNextQuarter) = dblValue
                                            Case "y"
                                                res.Values(QuoteProperty.EPSEstimateCurrentYear) = dblValue
                                            Case "z"
                                                res.Values(QuoteProperty.EPSEstimateNextYear) = dblValue
                                            Case "8e"
                                                res.AdditionalValues(StockScreenerProperty.EPS_NYCE) = dblValue
                                            Case "9v"
                                                res.AdditionalValues(StockScreenerProperty.SalesGrowthEstimate_ThisQuarter) = dblValue
                                            Case "8h"
                                                res.AdditionalValues(StockScreenerProperty.EarningsGrowthEstimate_ThisYear) = dblValue
                                            Case "9b"
                                                res.AdditionalValues(StockScreenerProperty.EarningsGrowthEstimate_NextYear) = dblValue
                                            Case "9u"
                                                res.AdditionalValues(StockScreenerProperty.EarningsGrowthEstimate_Next5Years) = dblValue
                                            Case "c"
                                                res.AdditionalValues(StockScreenerProperty.RevenueEstimate_ThisYear) = dblValue
                                            Case "1"
                                                res.AdditionalValues(StockScreenerProperty.SharesOutstanding) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))
                                            Case "2"
                                                res.Values(QuoteProperty.SharesFloat) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))
                                            Case "3"
                                                res.Values(QuoteProperty.ShortRatio) = dblValue
                                            Case "8g"
                                                res.AdditionalValues(StockScreenerProperty.SharesShortPriorMonth) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))
                                            Case "8m"
                                                res.AdditionalValues(StockScreenerProperty.SharesShort) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))
                                            Case "9d"
                                                res.AdditionalValues(StockScreenerProperty.HeldByInsiders) = dblValue
                                            Case "9n"
                                                res.AdditionalValues(StockScreenerProperty.HeldByInstitutions) = dblValue
                                            Case "4"
                                                res.Values(QuoteProperty.TrailingAnnualDividendYield) = dblValue
                                            Case "5"
                                                res.Values(QuoteProperty.TrailingAnnualDividendYieldInPercent) = dblValue
                                            Case "8a"
                                                res.AdditionalValues(StockScreenerProperty.OperatingMargin) = dblValue
                                            Case "8r"
                                                res.AdditionalValues(StockScreenerProperty.ProfitMargin_ttm) = dblValue
                                            Case "9f"
                                                res.AdditionalValues(StockScreenerProperty.EBITDAMargin_ttm) = dblValue
                                            Case "9k"
                                                res.AdditionalValues(StockScreenerProperty.GrossMargin_ttm) = dblValue
                                            Case "8f"
                                                res.Values(QuoteProperty.PriceBook) = dblValue
                                            Case "8f"
                                                res.AdditionalValues(StockScreenerProperty.CashPerShare) = dblValue
                                            Case "8l"
                                                res.AdditionalValues(StockScreenerProperty.TotalCash) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))
                                            Case "6"
                                                res.Values(QuoteProperty.BookValuePerShare) = dblValue
                                            Case "9e"
                                                res.AdditionalValues(StockScreenerProperty.TotalDebt) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))
                                            Case "9g"
                                                res.AdditionalValues(StockScreenerProperty.TotalDebtToEquityRatio) = dblValue
                                            Case "9h"
                                                res.AdditionalValues(StockScreenerProperty.CurrentRatio) = dblValue
                                            Case "9i"
                                                res.AdditionalValues(StockScreenerProperty.LongTermDebtToEquityRatio) = dblValue
                                            Case "9l"
                                                res.AdditionalValues(StockScreenerProperty.QuickRatio) = dblValue
                                            Case "w"
                                                res.Values(QuoteProperty.DilutedEPS) = dblValue
                                            Case "8i"
                                                res.AdditionalValues(StockScreenerProperty.EPS_mrq) = dblValue
                                            Case "0"
                                                res.AdditionalValues(StockScreenerProperty.Sales_ttm) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))
                                            Case "t"
                                                res.Values(QuoteProperty.EBITDA) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))
                                            Case "8n"
                                                res.AdditionalValues(StockScreenerProperty.GrossProfit) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))
                                            Case "8p"
                                                res.AdditionalValues(StockScreenerProperty.NetIncome) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))
                                            Case "9j"
                                                res.AdditionalValues(StockScreenerProperty.OperatingIncome) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))
                                            Case "8v"
                                                res.AdditionalValues(StockScreenerProperty.EarningsGrowth_Past5Years) = dblValue
                                            Case "9a"
                                                res.AdditionalValues(StockScreenerProperty.RevenueEstimate_ThisQuarter) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))
                                            Case "8q"
                                                res.AdditionalValues(StockScreenerProperty.RevenueEstimate_NextQuarter) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))
                                            Case "8s"
                                                res.AdditionalValues(StockScreenerProperty.SalesGrowthEstimate_NextQuarter) = dblValue
                                            Case "8t"
                                                res.AdditionalValues(StockScreenerProperty.SalesGrowthEstimate_ThisYear) = dblValue
                                            Case "8k"
                                                res.AdditionalValues(StockScreenerProperty.SalesGrowthEstimate_NextYear) = dblValue
                                            Case "8y"
                                                res.AdditionalValues(StockScreenerProperty.FreeCashFlow) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))
                                            Case "8z"
                                                res.AdditionalValues(StockScreenerProperty.OperatingCashFlow) = CLng(mFinanceHelper.GetMillionValue(values(p)) * (10 ^ 6))

                                        End Select

                                    End If
                                End If
                            Next
                        End If

                        results.Add(res)

                    End If
                Next

            End If
            Return New StockScreenerResponse(baseResp.Connection, results.ToArray)
        End Function


        Private Class AsyncArgs
            Inherits Base.DownloadEventArgs

            Public Criterias() As StockCriteriaDefinition
            Public Comparing As Boolean

            Public Sub New(ByVal userArgs As Object)
                MyBase.New(userArgs)
            End Sub
        End Class

    End Class

    Public Class StockScreenerDownloadCompletedEventArgs
        Inherits Base.DownloadCompletedEventArgs

        Private mCriterias() As StockCriteriaDefinition = Nothing

        Public ReadOnly Property Criterias As StockCriteriaDefinition()
            Get
                Return mCriterias
            End Get
        End Property

        Public Overloads ReadOnly Property Response As StockScreenerResponse
            Get
                Return CType(MyBase.Response, StockScreenerResponse)
            End Get
        End Property

        Friend Sub New(ByVal userArgs As Object, ByVal resp As StockScreenerResponse, ByVal criterias() As StockCriteriaDefinition)
            MyBase.New(userArgs, resp)
            mCriterias = criterias
        End Sub
    End Class


    Public Class StockScreenerResponse
        Inherits Base.Response

        Public Overloads ReadOnly Property Result() As StockScreenerData()
            Get
                Return CType(MyBase.Result, StockScreenerData())
            End Get
        End Property

        Friend Sub New(ByVal connInfo As Base.ConnectionInfo, ByVal results() As StockScreenerData)
            MyBase.New(connInfo, results)
        End Sub

    End Class


End Namespace




